import axios from 'axios'
import { getFullURL } from '@/utils/http'
const refreshurl = 'auth/refreshtoken'
const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_AXIOS_BASE_URL,
  // baseURL: 'https://yxttest100.shede.com.cn/api',
  adapter(config) {
    const { url, method, data, params, headers, baseURL, paramsSerializer } = config
    return new Promise((resolve, reject) => {
      uni.request({
        method: method!.toUpperCase() as any,
        url: getFullURL(baseURL || '', url!, params, paramsSerializer),
        header: headers,
        data,
        dataType: 'json',
        responseType: config.responseType,
        success: (res: any) => {
					resolve(res)
					// console.log('resresresresresresres', res)
					// if(res.data.code === 200){
					// 	resolve(res)
					// } else {
					// 	reject(res.data)
					// }
        },
        fail: (err: any) => {
          reject(err)
        }
      })
    })

  }
})

/**
 * 请求拦截
 */
instance.interceptors.request.use(
  (config: any) => {
    const token = uni.getStorageSync('token')
		config.headers['Authorization'] = 'Bearer ' + token
		config.headers['debug'] = 'true'
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
)
instance.interceptors.response.use((v: any) => {
	// console.log(getCurrentPages())
	// const pages = getCurrentPages();
	// let currentPage = ''
	// if (pages.length > 0) {
	// 	 currentPage = pages[pages.length - 1].route;
	// }
	if (v.statusCode === 401 || v.data.code === 401) {
		// uni.showToast({
		// 	icon:'none',
		// 	title: '请先登录',
		// 	duration: 1500,
		// });
		// setTimeout(()=>{
		// 	uni.navigateTo({ url: '/pages/wxLogin/wxLogin' })
		// }, 1500)
		return v.data
	} else if (v.data.code === 200) {
		return v.data
	} else {
		uni.showToast({
			icon:'none',
			title: v.data?.msg,
			duration: 1500
		});
	}
	return Promise.reject(v)
})

let loadingCount = 0
const http = {
  get: (url: any, params: any, loadingText = '加载中...', isShowLoading = true, isShowError = true) => {
    if (isShowLoading) {
      loadingCount++
      uni.showLoading({
        title: loadingText,
        mask: true
      })
    }
    return new Promise((resolve, reject) => {
      instance.get(url, { params })
    })

  },
  post: (url: any, data: any, loadingText = '加载中...', isShowLoading = true, isShowError = true) => {
    console.log(url)
		if (isShowLoading) {
      loadingCount++
      uni.showLoading({
        title: loadingText,
        mask: true
      })
    }
    return instance.post(url, data)
  },
	put: (url: any, data: any, loadingText = '加载中...', isShowLoading = true, isShowError = true) => {
	  console.log(url)
		if (isShowLoading) {
	    loadingCount++
	    uni.showLoading({
	      title: loadingText,
	      mask: true
	    })
	  }
	  return instance.post(url, data)
	},
}

export default instance
